#!/bin/bash
#
# Author: Yang, Ying-chao@gmail.com, 09- 6-2011
#
# When first used, you should empty /lib/systemd/system, then emerge systemd
# again to get a clean directory.
#

TOP=$PWD/service

DST="/lib/systemd/system/"

MD5="b64eb96b8653e0b768afdf610913cc4b"

for fn in `find /lib/systemd/system  -maxdepth 1 -type f -name "*.service"`;\
 do
    echo "Searching package containing $fn"
    qfile $fn > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "**** $fn : not declared by any packages";
        bname=$(basename $fn)
        if [ -e $TOP/$bname ]; then
            grep $MD5 $fn > /dev/null 2>&1
            if [ $? -eq 0 ]; then # Found package from my svn repository.
                rm -rf $fn;
            else
                echo "$bname existed, replace it with new one from SVN[Y/N]?"
                read answer
                case $answer in
                    Y|YES|y|yes)    rm -rf $fn;;
                    N|NO|n|no)     	echo "Skip $fn";;
                    *) 				echo -n "an unknown action";;
                esac
            fi
        else
            echo "Copying new file: $bname to SVN"
            mv $fn $TOP
            echo "#$MD5" >> $TOP/$bname
        fi
    fi
done

echo "Installing ..."
for src in $TOP/*.service; do
    bname=`basename $src`
    dstname=$DST/$bname
    echo "Installing: $bname";

    if [ -e $dstname ]; then
        grep $MD5 $fn > /dev/null 2>&1
        if [ $? -eq 0 ]; then
            rm $dstname -rf
            install -m 644 $src $DST
        else
            echo "$bname existed, replace it with new one from SVN[Y/N]?"
            read answer
            case $answer in
                Y|YES|y|yes)    rm -rf $dstname && install -m 644 $src $DST;;
                N|NO|n|no)     	echo "Skip $fn";;
                *) 				echo -n "an unknown action";;
            esac
        fi
    else
        install -m 644 $src $DST
    fi
done
